package com.ttc.mBackup.BackupSMS;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.ttc.mBackup.R;

public class RestoreSMSActivity extends ListActivity {
	
	private ImageView imgFile, imgPhone, imgLocation, imgRestoreMode, imgDelete;
    private TextView lblRestore, lblFilename, lblPhone, lblLocation, lblRestoreMode;
    private ImageButton btnRestore;
    ArrayList<String> phoneNumber;
    
    private ArrayList<HashMap<String,String>> list;
    private TextView lblVersion, lblSMS, lblTimeCreate;
    int smsCount;
    JSONArray jsonArray = null;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.s_layout_restore);
		
		IntializeSource();
		DialogFileSelectable();
		
		imgFile.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				DialogFileSelectable();
			}
		});
		imgLocation.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new CustomDialog(RestoreSMSActivity.this).createDialogLocationSelectable(lblLocation);
			}
		});
		imgRestoreMode.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				DialogModeSelectable();
			}
		});
		
		imgPhone.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				phoneNumber = new CustomDialog(RestoreSMSActivity.this).createDialogPhoneSelectable(lblPhone);
			}
		});
		
		imgDelete.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String filename = lblFilename.getText().toString();
				String msg = "Do you want to delete file \"" + filename + "\"?";
				DialogComfirm(msg);
				
			}
		});
		
		btnRestore.setOnClickListener(btnRestoreClick);
	}
	
	View.OnClickListener btnRestoreClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			String data = "Do you want restore message in to the phone with options?" + "\n\n" + 
					"Retore Mode: " + lblRestoreMode.getText().toString() + "\n" +
					"File Name: " + lblFilename.getText().toString() + "\n" + 
					"Location: " + lblLocation.getText().toString() + "\n" +
					"With People: " + lblPhone.getText().toString();
			String location = lblLocation.getText().toString();
			String filename = lblFilename.getText().toString();
			String mode = lblRestoreMode.getText().toString();
			if(filename.equals("") || filename == null){
				String msg = "You haven't choosen the filename?";
				new CustomDialog(RestoreSMSActivity.this).createDialogResult(msg);
			}else{
				new CustomDialog(RestoreSMSActivity.this, location, phoneNumber, filename).createDialogComfirm(data, mode);
			}
		}
	};
	/**
	 * 
	 */
	private void IntializeSource() {
		imgFile = (ImageView) findViewById(R.id.imgs_mainFileCreateable);
		imgPhone = (ImageView) findViewById(R.id.imgs_mainPhoneSelectable);
		imgLocation = (ImageView) findViewById(R.id.imgs_mainFileLocation);
		imgRestoreMode = (ImageView) findViewById(R.id.imgs_mainRestoreMode);
		imgDelete = (ImageView) findViewById(R.id.imgs_restore_delete);
		lblRestore = (TextView) findViewById(R.id.lbls_main_restore_title);
		lblFilename = (TextView) findViewById(R.id.lbls_mainFileCreateabe);
		lblPhone = (TextView) findViewById(R.id.lbls_mainPhoneSelectable);
		lblLocation = (TextView) findViewById(R.id.lbls_mainFileLocation);
		lblRestoreMode = (TextView) findViewById(R.id.lbls_mainRestoreMode);
		
		lblVersion = (TextView) findViewById(R.id.lbls_version);
        lblSMS = (TextView) findViewById(R.id.lbls_smsCount);
        lblSMS.setText("No file selected");
        lblTimeCreate = (TextView) findViewById(R.id.lbls_timecreate);
        
        
		btnRestore = (ImageButton) findViewById(R.id.btns_main_restore);
		
		lblFilename.setText("");
		phoneNumber = new ArrayList<String>();
		phoneNumber.add(0, "Check all");
	}	
	
	
	/**
	 * 
	 */
	private void DialogFileSelectable() {
		List<String> listFile = null;
    	listFile = new FileBrowser().getDir();
    	final String[] list = new String[listFile.size()];
    	listFile.toArray(list);
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	if(listFile.size() == 0){
			TextView text = new TextView(this);
			text.setText("No file here!");
			builder.setView(text);
			builder.setTitle("Error...");
			builder.setIcon(R.drawable.s_icon_error);
			builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}		
			});
		}else{
			builder.setSingleChoiceItems(list, 0, null);
			builder.setTitle("Choose File...");
			builder.setIcon(R.drawable.s_icon_json);
			builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					int itemChecked = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
					for (int i = 0; i < list.length; i++) {
						if (itemChecked == i) {
							lblFilename.setText(list[i]);
							setAdapter();
							imgDelete.setVisibility(View.VISIBLE);
						}
					}
				}
			});
			
			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
		}
    	
		AlertDialog dialog = builder.create();
		dialog.show();	
	}
	/**
	 * 
	 */
	private void DialogModeSelectable() {
		String[] choice = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		choice = new String[]{DialogCode.STRING_RESTORE_OVERRIDE, DialogCode.STRING_RESTORE_INCREMENTAL};
		builder.setTitle("Choose Restore Mode");
		builder.setIcon(R.drawable.s_icon_select_mode);
		final String[] temp = choice;
		
		builder.setSingleChoiceItems(choice, 0, null);
		
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				int itemChecked = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
				for (int i = 0; i < temp.length; i++) {
					if (itemChecked == i) {
						lblRestoreMode.setText(temp[i]);
						lblRestore.setText(temp[i] + " Restore");
						if(lblFilename.getText().equals("") || lblFilename.getText() == null){
							DialogFileSelectable();
						}
					}
				}
			}
		});
		
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		
		AlertDialog dialog = builder.create();
		dialog.show();
	}
	
	private void DialogComfirm(String msg){
		TextView textview = new TextView(RestoreSMSActivity.this);
		textview.setText(msg);
		AlertDialog.Builder builder = new AlertDialog.Builder(RestoreSMSActivity.this);
		builder.setTitle("Comfirm?");
		builder.setIcon(R.drawable.s_icon_question);
		builder.setView(textview);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				ProgressDialogPerform progress = new ProgressDialogPerform(RestoreSMSActivity.this);
				progress.setBackupMode(DialogCode.CODE_PROGRESS_DELETE);
				progress.setFilename(lblFilename.getText().toString());
				progress.onCreate();
				
				lblFilename.setText("");
				imgDelete.setVisibility(View.INVISIBLE);
				setListAdapter(null);
				lblVersion.setText("");
				lblTimeCreate.setText("");
				lblSMS.setText("No file selected");			
			}
		});
		
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		AlertDialog dialog = builder.create();
		dialog.show();
	}
	/**
	 * 
	 */
	private void setAdapter() {
        String filename = lblFilename.getText().toString();
        list = new ArrayList<HashMap<String,String>>();
        
        
        String jsonString = null;
		try {
			jsonString = new FileBrowser(filename).ReadBackupFile();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
    	try {	
            lblFilename.setText(filename);
        	JSONObject jsonObject = new JSONObject(jsonString);
        	smsCount = jsonObject.getInt("smses");
        	lblVersion.setText("Version: " + String.valueOf(jsonObject.getInt("version")));
			lblTimeCreate.setText("Created Time: " + jsonObject.getString("backupTime"));
			jsonArray = jsonObject.getJSONArray("sms");
		} catch (JSONException e) {
			e.printStackTrace();
		}    
        
    	SimpleAdapter adapter = new SimpleAdapter(
            		this,
            		list,
            		R.layout.s_layout_listrow,
            		new String[] {"id", "address","read","date", "body"},
            		new int[] {R.id.lbls_row_id,
            				R.id.lbls_row_address, 
            				R.id.lbls_row_read, 
            				R.id.lbls_row_date, 
            				R.id.lbls_row_body}
           );     
        populateList();
        setListAdapter(adapter);
	}
	/**
	 * 
	 */
	private void populateList() {
    	HashMap<String, String> map;
    	int unreadCount = 0;
		int inboxCount = 0;
		int sentboxCount = 0;
    	for (int i = 0; i < smsCount; i++) {
    		map = new HashMap<String, String>();
            String id;
			int read, type;			
            String body = "", date = "", status = "";
            String address = "";
            try {
            	id = (String) ("SMS #" + jsonArray.getJSONObject(i).getString("id"));
				read = jsonArray.getJSONObject(i).getInt("read");
				if(read == 1){
					status = "Status:  Readed";
				}else{
					status = "Status: Unread";
					unreadCount++;
				}
				type = jsonArray.getJSONObject(i).getInt("type");
	            body = "Content: " + jsonArray.getJSONObject(i).getString("body");
	            date = "Date: " + jsonArray.getJSONObject(i).getString("date");
	            if(type == 1){
	            	address = "Inbox: " + jsonArray.getJSONObject(i).getString("address");
	            	inboxCount++;
	            }else if(type == 2){
	            	address = "Sentbox: " + jsonArray.getJSONObject(i).getString("address");
	            	sentboxCount++;
	            }
	            map.put("id", id);
	            map.put("address", address);
	            map.put("read", status);
	            map.put("date", date);
	            map.put("body", body);
	            list.add(map);
			} catch (JSONException e) {
				e.printStackTrace();
			}
    	}
    	String sms = "SMS: " + String.valueOf(smsCount) + " (" 
    						+ "Unread: " + unreadCount + ", Inbox: "
    						+ inboxCount + ", Sentbox: " + sentboxCount + ")";					
        lblSMS.setText(sms);
    }
}
